<?php
class wxpay{

	private $pay_success_url = '';//支付成功请求地址（微信前端主动请求：更新本地订单状态）
	private $pay_wx_notify_url = '';//支付成功请求地址（微信后端主动请求：更新本地订单状态）
	private $pay_fail_url = '';//支付失败返回地址
	
	/**
	 * 初始化
	 * order['goods_name']
	 * order['order_sn']
	 * order['order_amount']
	 */
	public function __construct($order=array()){
		if(!empty($order)){
			$this->order = $order;
			$this->pay_success_url = "http://".$_SERVER['HTTP_HOST']."/baoming/api/payment/wxpay/return_url.php?out_trade_no=".$this->order['order_sn'];
			$this->pay_wx_notify_url = "http://".$_SERVER['HTTP_HOST']."/baoming/api/payment/wxpay/notify_url.php";
			$this->pay_fail_url = '';
		}
	}

	/**
	 * 调用微信JS api 支付
	 * @return string
	 */
	public function get_payurl(){
		require_once "lib/WxPay.Api.php";
		require_once "example/WxPay.JsApiPay.php";
		require_once 'example/log.php';
		//初始化日志
		$logHandler= new CLogFileHandler(str_replace('\\','/',dirname(__FILE__)).'/logs/'.date('Y-m-d').'.log');
		$log = Log1::Init($logHandler, 15);
		
		//②、统一下单
		$input = new WxPayUnifiedOrder();
		$input->SetBody($this->order['goods_name']);//设置商品或支付单简要描述
		//设置附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
		$input->SetAttach("");
		//商户系统内部的订单号,32个字符内、可包含字母,
		$input->SetOut_trade_no($this->order['order_sn']);
		//订单总金额，只能为整数，详见支付金额(单位分)
		$input->SetTotal_fee(floor($this->order ['order_amount']*100));
		//订单生成时间，格式为yyyyMMddHHmmss，如2009年12月25日9点10分10秒表示为20091225091010
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag("");//设置商品标记，代金券或立减优惠功能的参数，说明详见代金券或立减优惠
		$input->SetNotify_url($this->pay_wx_notify_url);
		$input->SetTrade_type("JSAPI");
		$input->SetOpenid($openId);
		$order = WxPayApi::unifiedOrder($input);
		try {
			$jsApiParameters = $tools->GetJsApiParameters($order);
		}catch (Exception $e) {
			@header("Location: ".$this->pay_success_url);
			exit;
		}
		//获取共享收货地址js函数参数
		$editAddress = $tools->GetEditAddressParameters();
		echo '<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/> <title>英才学校</title>';
		echo '<script type="text/javascript">';
		//调用微信JS api 支付
		echo 'function onBridgeReady(){WeixinJSBridge.invoke("getBrandWCPayRequest",';
		echo $jsApiParameters.',';
		echo 'function(res){';
		echo 'if(res.err_msg == "get_brand_wcpay_request:ok" ) {';
		echo "location.href='".$this->pay_success_url."';";//js返回成功，但还需查询订单状态
		echo '}else{';
		echo "location.href='".$this->pay_fail_url."';";//js返回未支付，直接跳转到
		echo '}';
		echo '} );}';
		echo 'if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener("WeixinJSBridgeReady", onBridgeReady, false);}else if (document.attachEvent){document.attachEvent("WeixinJSBridgeReady", onBridgeReady); document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);}}else{onBridgeReady();}';
		echo '</script>';
		echo '</head><body></body></html>';
		
	}
}
?>